package com.codebox.ourblogs.http;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;

import com.codebox.common.base.BaseResult;
import com.codebox.common.base.Resource;
import com.codebox.common.http.ApiCallback;
import com.codebox.common.util.LogUtils;
import com.codebox.ourblogs.bean.BlogBean;

import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

/**
 * @author Able
 * @date 2018/12/19
 */
public class HttpClient {
    private static final HttpClient instance = new HttpClient();

    private HttpClient() {

    }

    public static HttpClient getInstance() {
        return instance;
    }

    private Api api = RetrofitFactory.getInstance().create(Api.class);

    public LiveData<Resource<List<BlogBean>>> getPageBlog(int pageNo) {
        final MutableLiveData<Resource<List<BlogBean>>> liveData = new MutableLiveData<>();
        api.getPageBlogs(pageNo).enqueue(new ApiCallback<BaseResult<List<BlogBean>>>() {
            @Override
            public void onResponse(Call call, BaseResult result) {
                liveData.setValue(Resource.response(result));
            }

            @Override
            public void onError(Call call, Throwable t) {
                liveData.setValue(Resource.error(t));
            }
        });
        return liveData;
    }

    public LiveData<Resource<List<BlogBean>>> searchBlog(HashMap map) {
        final MutableLiveData<Resource<List<BlogBean>>> liveData = new MutableLiveData<>();

        api.searchBlogs(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResult<List<BlogBean>>>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResult<List<BlogBean>> listBaseResult) {
                        liveData.setValue(Resource.response(listBaseResult));
                    }

                    @Override
                    public void onError(Throwable e) {
                        liveData.setValue(Resource.error(e));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        return liveData;
    }
}
